package com.walnut.action.rest.controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.walnut.model.Immortal;
import com.walnut.service.ImmortalManager;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import java.util.List;

/**
 * Created by parker on 15/4/12.
 */
public class ImmortalsController extends ActionSupport implements ModelDriven<Object>{
    private ImmortalManager immortalManager;
    private Integer id;
    //Struts models
    private Immortal immortal = new Immortal();
    private List<Immortal> immortalList;

    //The fields matches the developer's needs
    private String fields;

    /**
     * Handles /immortals/{id} GET requests
     * @return  Response in the way of http headers
     */
    public HttpHeaders view(){
        if(null == fields || fields.length() == 0) {
            immortal = immortalManager.getImmortal(id);
        }
        else{
            immortal = immortalManager.getImmortal(id, fields);
        }
        return new DefaultHttpHeaders("view");
    }

    /**
     * Handles /immortals GET requests
     * @return Response in the way of http headers
     */
    public HttpHeaders index(){
        immortalList = immortalManager.getAllImmortals();
        return new DefaultHttpHeaders("index").disableCaching();
    }

    public void setFields(String fields) {
        this.fields = fields;
    }

    @Override
    public Object getModel() {
        return immortalList != null? immortalList : immortal;
    }

    public void setImmortalManager(ImmortalManager immortalManager){
        this.immortalManager = immortalManager;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public List<Immortal> getImmortalList() {
        return immortalList;
    }

    public void setImmortalList(List<Immortal> immortalList) {
        this.immortalList = immortalList;
    }
}
